package com.example.controller.config;

import com.example.common.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.UnexpectedTypeException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //参数校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Message bindExceptionHandler(MethodArgumentNotValidException e){
        log.info("出现异常，{}",e);
        return Message.error(500,e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * bean参数验证.
     *
     * @param e RuntimeException
     * @return String
     */
    @ExceptionHandler(BindException.class)
    public Message validExceptionHandler(BindException e) {
        log.info("出现异常，{}",e);
        return Message.error(500,e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 参数类型错误
     */
    @ExceptionHandler(UnexpectedTypeException.class)
    public Message validExceptionHandler(UnexpectedTypeException e) {
        log.info("出现异常，{}",e);
        return Message.error(500,e.getMessage());
    }

    /**
     * 总的异常处理
     */
    @ExceptionHandler(Exception.class)
    public Message handleException(Exception e) {
        log.info("出现异常，{}",e.getClass());
        return Message.error(500,e.getMessage());
    }
}
